package com.zrkizzy.seckill.controller.system;

import com.zrkizzy.seckill.entity.User;
import com.zrkizzy.seckill.service.core.IGoodsService;
import com.zrkizzy.seckill.service.tool.IRedisService;
import com.zrkizzy.seckill.vo.common.Result;
import com.zrkizzy.seckill.vo.system.DetailVO;
import com.zrkizzy.seckill.vo.system.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;

import static com.zrkizzy.seckill.constant.CommonConst.GOODS_LIST;
import static com.zrkizzy.seckill.constant.CommonConst.USER;
import static com.zrkizzy.seckill.constant.TimeConst.ONE_MINUTE;

/**
 * 商品前端控制器
 *
 * @author zhangrongkang
 * @since 2023/3/21
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IRedisService redisService;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private IGoodsService goodsService;

    /**
     * 跳转到商品页
     *
     * @return 商品页
     */
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
        // Redis中读取缓存页面
        String goodsListHtml = (String) redisService.get(GOODS_LIST);
        if (StringUtils.hasLength(goodsListHtml)) {
            return goodsListHtml;
        }
        // 将用户对象添加到页面中
        model.addAttribute(USER, user);
        // 将商品列表存储到页面中
        model.addAttribute(GOODS_LIST, goodsService.listGoods());
        // 如果为空则手动渲染
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        String html = thymeleafViewResolver.getTemplateEngine().process("web/common/goodsList", webContext);
        if (StringUtils.hasLength(html)) {
            // 存储渲染的数据到Redis中
            redisService.set(GOODS_LIST, html, ONE_MINUTE);
        }
        return html;
    }

    /**
     * 跳转商品详情页
     *
     * @param user 当前登录用户对象
     * @param goodsId 商品ID
     * @return 商品详情页
     */
    @RequestMapping(value = "/toDetail/{goodsId}")
    public Result toDetail(User user, @PathVariable Long goodsId) {
        // 根据商品ID查询商品详情
        GoodsVO goodsVO = goodsService.getGoodsById(goodsId);
        // 获取商品秒杀活动的开始时间和结束时间
        LocalDateTime startTime = goodsVO.getStartTime();
        LocalDateTime endTime = goodsVO.getEndTime();
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 定义秒杀状态
        int seckillStatus;
        // 定义秒杀倒计时
        long remainSeconds = 0;
        // 秒杀还未开始
        if (currentTime.isBefore(startTime)) {
            seckillStatus = 0;
            // 获取活动开始的秒数
            remainSeconds = Math.abs(Duration.between(startTime, currentTime).toSeconds());
        } else if (currentTime.isAfter(endTime)) {
            // 秒杀已经结束
            seckillStatus = 2;
            remainSeconds = -1;
        } else {
            // 秒杀正在进行中
            seckillStatus = 1;
        }
        // 定义商品详情返回对象
        DetailVO detailVO = DetailVO.builder()
                .user(user)
                .goodsVO(goodsVO)
                .seckillStatus(seckillStatus)
                .remainSeconds(remainSeconds)
                .build();

        return Result.success(detailVO);
    }
}
